package cn.scw.framework.protocol.udp;

import cn.scw.common.utils.spring.SpringUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.InetSocketAddress;

/**
 * udpserver的管理器，拥有server的实例及上下文，对server的顶级管理提供操作接口
 */
@Component
public class UdpServerManager {

    //获取单例
    public static UdpServerManager getManager(){
        return SpringUtils.getBean(UdpServerManager.class);
    }

    @Value("${udpserver.port}")
    private int port;

    private Channel channel=null;

    //启动udp-server
    public void start(){

        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
        try {
            Bootstrap b = new Bootstrap(); // (2)
            b.group(bossGroup)
                    .channel(NioDatagramChannel.class) // (3) udp服务
                    .handler(new UdpDataHandler())//数据处理
                    .option(ChannelOption.SO_BROADCAST, true);//开启广播
            try {
                Channel channel=b.bind(port).channel();
                this.channel=channel;
                ChannelFuture f=channel.closeFuture().sync().await();// 开启监听
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } finally {
            bossGroup.shutdownGracefully();
        }
    }

    public void send(byte[] content,InetAddress destIp,int destPort){
        try {
            InetSocketAddress dest=new InetSocketAddress(destIp.getHostAddress(),destPort);
            channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(content),dest)).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
